package org.theSeed.base.pojo.config;

import cn.hutool.core.util.ObjectUtil;
import lombok.Getter;

import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.ForkJoinWorkerThread;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 自定义线程工厂
 */
public class NameThreadFactory implements ThreadFactory, ForkJoinPool.ForkJoinWorkerThreadFactory {
    public NameThreadFactory(String name) {
        this.namePrefix = name + "-thread-";
    }

    @Getter
    private String namePrefix;

    private AtomicInteger counter = new AtomicInteger(1);

    @Override
    public Thread newThread(Runnable r) {
        Thread thread = new Thread(r);
        thread.setName(getThreadName());
        return thread;
    }

    @Override
    public ForkJoinWorkerThread newThread(ForkJoinPool forkJoinPool) {
        // 使用基础线程池的线程创建逻辑
        ForkJoinWorkerThread thread = ForkJoinPool.defaultForkJoinWorkerThreadFactory.newThread(forkJoinPool);
        thread.setName(getThreadName());
        return thread;
    }

    /**
     * 获取线程名称
     * @return
     */
    public String getThreadName(){
        return namePrefix + counter.getAndIncrement();
    }

    /**
     * 默认线程工厂名称
     */
    public static String defaultThreadFactoryName = "SEED";

    /**
     * 默认线程工厂
     */
    private static NameThreadFactory defaultThreadFactory;

    public static NameThreadFactory getDefaultThreadFactory(){
        if (ObjectUtil.isNotNull(defaultThreadFactory)){
            return defaultThreadFactory;
        }else{
            return createNameThreadFactory();
        }
    }

    /**
     * 创建默认线程工厂
     * @return
     */
    private static synchronized NameThreadFactory createNameThreadFactory() {
        if (ObjectUtil.isNotNull(defaultThreadFactory)){
            return defaultThreadFactory;
        }else{
            return new NameThreadFactory(defaultThreadFactoryName);
        }
    }
}
